from django.db import models
from utils.models import BaseModel # 引入自定义model继承类 
from django.contrib.auth.models import AbstractUser # 继承了AbstractBaseUser，作为一个抽象类它包含完整的用户模型的字段
from django_prometheus.models import ExportModelOperationsMixin

class UserProfile(ExportModelOperationsMixin('UserProfile'), AbstractUser):
# class UserProfile(AbstractUser):
    """ 用户信息 """
    name = models.CharField(max_length=20, default='', blank=True, verbose_name='真实姓名')
    position = models.CharField(max_length=20, default='',blank=True,null=True,verbose_name="职位")
    mobile = models.CharField(max_length=11, unique=True, null=True, blank=True, default=None, verbose_name='手机号码')
    image = models.ImageField(upload_to='avatar/%Y/%m', default='avatar/default.jpeg', blank=True, verbose_name='头像')
    roles = models.ManyToManyField('Roles', db_table='cmdb_oauth_users_to_system_roles', blank=True,
                                   verbose_name='角色')
    # team= models.ForeignKey('Team', null=True, blank=True, on_delete=models.SET_NULL,
    #                                verbose_name='团队')
    department = models.ForeignKey('Departments', null=True, blank=True, on_delete=models.SET_NULL,
                                   verbose_name='部门')
    class Meta:
        verbose_name = '用户'
        verbose_name_plural = verbose_name
        ordering = ['id']

    def __str__(self):
        return self.username

    def _get_user_permissions(self):
        permissions = []
        # 获取用户权限
        permissions = list(filter(None, set(self.roles.values_list('permissions__sign', flat=True))))
        if 'admin' in self.roles.values_list('name', flat=True):
            permissions.append('admin')

        if self.username == 'admin':
            permissions.append('admin')

        for  name in self.roles.values_list('name', flat=True):
            if name:
                permissions.append(name)
        return permissions

    def get_user_info(self):
        # 获取用户信息
        user_info = {
            'id': self.pk,
            'username': self.username,
            'name': self.name,
            'job':self.position,
            'avatar': '/media/' + str(self.image),
            'email': self.email,
            'permissions': self._get_user_permissions(),
            'department': self.department.name if self.department else '',
            'mobile': '' if self.mobile is None else self.mobile
        }
        return user_info


class Permissions(BaseModel):
    """ 权限 """
    method_choices = (
        ('POST', '增'),
        ('DELETE', '删'),
        ('PUT', '改'),
        ('GET', '查'),
        ('PATCH', '局部改'),
        ('head','HEAD'),
        ('options','OPTIONS'),
        ('all','ALL')
    )

    name = models.CharField(max_length=30, verbose_name='权限名')
    sign = models.CharField(max_length=30, unique=True, verbose_name='权限标识')
    menu = models.BooleanField(verbose_name='是否为菜单')  # True为菜单,False为接口
    method = models.CharField(max_length=8, blank=True, default='', choices=method_choices, verbose_name='方法')
    path = models.CharField(max_length=200, blank=True, default='', verbose_name='请求路径正则')
    pid = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, verbose_name='父权限')

    def __str__(self):
        return self.name
    class Meta:
        verbose_name = '权限'
        verbose_name_plural = verbose_name
        ordering = ['id']


class Roles(BaseModel):
    """ 角色 """
    name = models.CharField(max_length=32, unique=True, verbose_name='角色')
    permissions = models.ManyToManyField('Permissions', db_table='system_roles_to_system_permissions',                          blank=True, verbose_name='权限')
    desc = models.CharField(max_length=50, blank=True, default='', verbose_name='描述')

    def __str__(self):
        return self.name

    class Meta:
        # db_table = 'cmdb_system_roles'
        verbose_name = '角色'
        verbose_name_plural = verbose_name
        ordering = ['id']



# class Team(BaseModel):
#     department_id = models.ForeignKey('Department',on_delete=models.PROTECT, blank=True,
#                                       null=True)
#     class Meta:
#         ordering = ['id']
#         db_table = 'oauth_team'


class Departments(BaseModel):
    """
    组织架构 部门
    """
    name = models.CharField(max_length=32, unique=True, verbose_name='部门')
    pid = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, verbose_name='父部门') # 级联删除，当删除主表的数据时候从表中的数据也随着一起删除
    index = models.IntegerField(default=99, verbose_name='分类排序')

    def __str__(self):
        return self.name
    class Meta:
        verbose_name = '部门'
        verbose_name_plural = verbose_name
        ordering = ['index']